package com.chao.stucture.queue;

import java.util.Queue;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/11/27
 */
public class LinkedQueue<E> {

    private Node<E> head;  // 队头
    private Node<E> tail;  // 队尾
    private int size;

    static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value) {
            this.value = value;
        }
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 入队一个元素
     * @param element
     */
    public void enqueue(E element) {
        Node<E> newNode = new Node<>(element);
        if (this.head == null) {
            head = tail = newNode;
        } else {
            tail.next = newNode;
            tail = newNode;
        }
        size ++;
    }

    /**
     * 出队一个元素
     * @return
     */
    public E dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空！");
        }
        E element = head.value;
        head = head.next;
        // 当队列中只有一个元素时，head == null
        if (head == null) {
            tail = null;
        }
        size --;
        return element;
    }

    /**
     * 查看队头元素
     * @return
     */
    public E peek() {
        if (head == null) {
            return null;
        }
        return head.value;
    }

    public int size() {
        return size;
    }

    public void print() {
        Node<E> currNode = head;
        StringBuilder sb = new StringBuilder();
        while (currNode != tail) {
            sb.append(currNode.value);
            if (currNode.next != null) {
                sb.append("->");
            }
            currNode = currNode.next;
        }
        System.out.println(sb);
    }

    public static void main(String[] args) {
        LinkedQueue<String> linkedQueue = new LinkedQueue<>();
        linkedQueue.enqueue("A");
        linkedQueue.enqueue("B");
        linkedQueue.enqueue("C");
        linkedQueue.print();
        System.out.println("队头元素是：" + linkedQueue.peek());
    }

}
